//
//  PlayMusciViewController.m
//  悦享
//
//  Created by dllo on 16/3/23.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "PlayMusciViewController.h"
#import <UIImageView+WebCache.h>
#import "SongModel.h"
#import "SongLevelModel.h"
#import "HGAVPlayerManager.h"
#import "HGMusicUrlHnadel.h"
@interface PlayMusciViewController ()

@property (nonatomic, assign) BOOL isSelect;/**<  判断按钮是否被选中 */

@property (nonatomic, retain) UIImageView *backImage;/**<  背景图片 */
@property (nonatomic, retain) UIImageView *alphaImageViewl;/**<  半透明图片 */
@property (nonatomic, retain) UIVisualEffectView *effectview;/**<  模糊视图 */

@property (nonatomic, retain) UIImageView *topImageView;/**<  旋转的图片 */

@property (nonatomic, retain) UIButton *disMissButton;/**<  返回button */

@property (nonatomic, retain) UILabel *nameLabel;/**<  歌名label */

@property (nonatomic, retain) UILabel *singerLabel;/**<  歌手label */

@property (nonatomic, retain) UIButton *playButtonl; /**<  播放按钮 */


@property (nonatomic, retain) UIButton *nextButton;/**<  上一曲button */

@property (nonatomic, retain) UIButton *next2Button;/**<  下一曲 */

@property (nonatomic, retain) UIButton *caiDanButton;/**<  菜单button */

@property (nonatomic, assign) BOOL isPlay;/**<  播放判断 */

@property (nonatomic, retain) UISlider *playProgress;/**<  播放进度 */

@property (nonatomic, retain) UILabel *initialLabel;/**<  播放时间 */

@property (nonatomic, retain) UILabel *totalLabel;/**<  总时间 */

@property (nonatomic, retain) NSMutableArray *dataArr;/**<  数据源数组 */



@property (nonatomic, retain) UIButton *XunHuanButton;/**<  列表循环按钮 */

@property (nonatomic, retain) UIButton *danQuXunHanButton;/**<  单曲魂环按钮 */

@end

@implementation PlayMusciViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

- (void)setModel:(SongModel *)model{
    _model = model;
    [self playSongs];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  
    [self createBackImage];
    [self createSubViews];
    [self craetePlaySubView];
    
    [_topImageView sd_setImageWithURL:[NSURL URLWithString:_model.picUrl] placeholderImage:[UIImage imageNamed:@"2"]];
    _nameLabel.text = _model.name;
    _singerLabel.text = _model.singerName;
    [_backImage sd_setImageWithURL:[NSURL URLWithString:_model.picUrl] placeholderImage:[UIImage imageNamed:@"place"]];
    //让图片旋转
    _isPlay = YES;
    
    //点击下一曲返回的刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTable:) name:@"change" object:nil];
}
/**
 *  /点击下一曲返回的刷新数据
 *
 *  @param notification 传过来index刷新界面
 */
- (void)changeTable:(NSNotification *)notification{
    
     SongModel *model = (SongModel *)notification.object;
    
    /**
     *  重新赋值
     */
    [_topImageView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"2"]];
    _nameLabel.text = model.name;
    _singerLabel.text = model.singerName;
    [_backImage sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"place"]];
    
    [self playSongs];
}

/**
 *  创建播放按钮
 */
- (void)craetePlaySubView{
    //创建播放按钮下面的view
    UIView *playView = [[UIView alloc] initWithFrame:CGRectMake((SREEN_WIDTH - 80)/2, _topImageView.frame.origin.y + 300 + 80, 80, 80) ];
    playView.layer.cornerRadius = 40;
    playView.layer.masksToBounds = YES;
    playView.backgroundColor = [UIColor colorWithRed:arc4random()%(255 - 0 + 1)/255.0 green:arc4random()%(255 - 0 + 1)/255.0 blue:arc4random()%(255 - 0 + 1)/255.0 alpha:1];
    
    [self.view addSubview:playView];
    //创建播放按钮
    self.playButtonl = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButtonl.frame = CGRectMake((SREEN_WIDTH - 50)/2, _topImageView.frame.origin.y + 300-4 + 100, 50, 50) ;
    [_playButtonl addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [_playButtonl setImage:[UIImage imageNamed:@"111.png"] forState:UIControlStateNormal];
    
    
    
    [self.view addSubview:_playButtonl];
    
    
    /**<  创建上一曲button */
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(SREEN_WIDTH / 5, _topImageView.frame.origin.y + 300 + 100, 50, 50);
    
    [_nextButton addTarget:self action:@selector(nextButton:) forControlEvents:UIControlEventTouchUpInside];
    [_nextButton setImage:[UIImage imageNamed:@"iconfont-ttpodicon.png"] forState:UIControlStateNormal];
    
    [self.view addSubview:_nextButton];
    
    /**<  创建下一曲button */
    self.next2Button = [UIButton buttonWithType:UIButtonTypeCustom];
    _next2Button.frame = CGRectMake(SREEN_WIDTH / 5 + (SREEN_WIDTH / 2), _topImageView.frame.origin.y + 300 + 100, 50, 50);
    [_next2Button addTarget:self action:@selector(xiaButton:) forControlEvents:UIControlEventTouchUpInside];
    [_next2Button setImage:[UIImage imageNamed:@"iconfont-ttpodicon-2.png"] forState:UIControlStateNormal];
    [self.view addSubview:_next2Button];
    
    
    self.playProgress = [[UISlider alloc] initWithFrame:CGRectMake((SREEN_WIDTH - (SREEN_WIDTH - 120))/2, (_topImageView.frame.origin.y + 300 + 40), (SREEN_WIDTH - 120), 30)];
    [self.view addSubview:_playProgress];
    [_playProgress addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    
    /**<  创建显示时间的label */
    self.initialLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (_topImageView.frame.origin.y + 300 + 40), 50, 30)];
    self.initialLabel.text = @"--:--";
    self.initialLabel.textAlignment = NSTextAlignmentCenter;
    self.initialLabel.textColor = [UIColor whiteColor];
    self.initialLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_initialLabel];
    
    
    self.totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(SREEN_WIDTH - 50, (_topImageView.frame.origin.y + 300 + 40), 50, 30)];
    self.totalLabel.text = @"--:--";
    self.totalLabel.textAlignment = NSTextAlignmentCenter;
    self.totalLabel.font = [UIFont systemFontOfSize:12];
    self.totalLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_totalLabel];
}

/**<  创建子控件 */
- (void)createSubViews{
    
   
    self.topImageView = [[UIImageView alloc] init];
    _topImageView.frame = CGRectMake(0, 0, 300,300);
    _topImageView.center = _effectview.center;
    
    _topImageView.layer.cornerRadius = 150;
    _topImageView.backgroundColor = [UIColor clearColor];
    _topImageView.layer.masksToBounds = YES;
    _topImageView.layer.borderColor = [UIColor cyanColor].CGColor;
    _topImageView.layer.borderWidth = 1;
    [self.view addSubview:_topImageView];
    
    
    /**<  创建一个半透明的view */
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH, 100)];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.2;
    [self.view addSubview:view];
    
    
    /**<  创建返回buton */
    self.disMissButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _disMissButton.frame = CGRectMake(30, 30, 30, 30);
    _disMissButton.backgroundColor = [UIColor clearColor];
    [_disMissButton setImage:[UIImage imageNamed:@"iconfont-yincangtubiao"] forState:UIControlStateNormal];
    [_disMissButton addTarget:self action:@selector(disMissButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_disMissButton];
    
    
    /**<  创建名字label */
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 30, 200, 50)];
    _nameLabel.backgroundColor = [UIColor clearColor];
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont systemFontOfSize:22];
  
       [self.view addSubview:_nameLabel];
    
    /**<  创建歌手label */
    self.singerLabel = [[UILabel alloc] initWithFrame:CGRectMake(73, 68, 100, 30)];
    _singerLabel.backgroundColor = [UIColor clearColor];
    _singerLabel.font = [UIFont systemFontOfSize:12];
    _singerLabel.textColor = [UIColor whiteColor];
    

    [self.view addSubview:_singerLabel];

  
    /**<  创建单曲循环按钮 */
    self.danQuXunHanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _danQuXunHanButton.frame = CGRectMake(SREEN_WIDTH - 80, SREEN_HEIGHT - 60, 50, 40);
    _danQuXunHanButton.layer.cornerRadius = 9;
    _danQuXunHanButton.layer.masksToBounds = YES;
    _danQuXunHanButton.backgroundColor = [UIColor blackColor];
    _danQuXunHanButton.alpha = 0.4;

    [_danQuXunHanButton setImage:[UIImage imageNamed:@"iconfont-danquxunhuan.png"] forState:UIControlStateNormal];
    [_danQuXunHanButton addTarget:self action:@selector(danQuXunHanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_danQuXunHanButton];
    
//    //从本地取出是否正在播放进行判断，让图片旋转
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isPlay"]) {
//        //推迟0.1秒让图片旋转
//        [self performSelector:@selector(startAnimation1111) withObject:nil afterDelay:0.1];
//    }
    
   [self performSelector:@selector(startAnimation1111) withObject:nil afterDelay:0.1];
    
}

/**<  单曲循环按钮 */
- (void)danQuXunHanButtonAction:(UIButton *)button{
    if (_isSelect == NO) {
        [_danQuXunHanButton setImage:[UIImage imageNamed:@"iconfont-danquxunhuan.png"] forState:UIControlStateNormal];
        _danQuXunHanButton.backgroundColor = [UIColor blueColor];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"danQuXunHuan" object:nil];
        
    }else {
        [_danQuXunHanButton setImage:[UIImage imageNamed:@"iconfont-danquxunhuan-2.png"] forState:UIControlStateNormal];
        _danQuXunHanButton.backgroundColor = [UIColor blackColor];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CnadledanQuXunHuan" object:nil];
        
    }
    _isSelect = !_isSelect;
}
/**<  上一曲 */
- (void)nextButton:(UIButton *)button{
    //发送上一曲通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"musicButtonLast" object:nil];
}

/**<  下一曲 */
- (void)xiaButton:(UIButton *)button{
    //发送下一曲同时
    [[NSNotificationCenter defaultCenter] postNotificationName:@"musicButtonNext" object:nil];
}
//slider点击方法
- (void)sliderAction:(UISlider *)slider{
    
    [[HGAVPlayerManager shareHGavPlayerManager] seekToTime:slider.value];
    
    
}

/**<  播放按钮点击方法 */
- (void)playButton:(UIButton *)button{
    
    if (_isPlay == YES) {
        [_playButtonl setImage:[UIImage imageNamed:@"iconfont-bofang.png"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGavPlayerManager] pause];
        // 暂停
        CFTimeInterval stopTime = [self.topImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        // 设置动画速度
        self.topImageView.layer.speed = 0;
        // 保存时间的偏移量
        self.topImageView.layer.timeOffset = stopTime;

    }else{
        [_playButtonl setImage:[UIImage imageNamed:@"111.png"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGavPlayerManager] play];
        // 找到时间偏移量
        CFTimeInterval stopTime = self.topImageView.layer.timeOffset;
        // 速度设置为1
        self.topImageView.layer.speed = 1;
        // beginTime 重置
        self.topImageView.layer.beginTime = 0;
        self.topImageView.layer.timeOffset = 0;
        // 设置开始的时间
        self.topImageView.layer.beginTime = [self.topImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        
        [[HGAVPlayerManager shareHGavPlayerManager] seekToTime:self.playProgress.value];
        
    }
    
    _isPlay = ! _isPlay;
    
}
//0.1秒block回调的方法
- (void)playTimer:(CGFloat)timer{
    
    //暂停
    CFTimeInterval stopTime = [self.topImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //设置动画时间
    self.topImageView.layer.speed = 0;
    //保存时间偏移量
    self.topImageView.layer.timeOffset = stopTime;
    self.playProgress.value = timer / [HGAVPlayerManager shareHGavPlayerManager].sumTime;//给滑竿赋值
    
    //找到时间偏移量
    CFTimeInterval stopTimer1 = self.topImageView.layer.timeOffset;
    //速度设置为1
    self.topImageView.layer.speed = 1;
    //beginTime重置
    self.topImageView.layer.beginTime = 0;
    self.topImageView.layer.timeOffset = 0;
    //设置开始时间
    self.topImageView.layer.beginTime = [self.topImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTimer1;
    
}

#pragma mark 获取字符串时间

- (NSString *)timeToString:(CGFloat)time{
    
    NSInteger minutes = (NSInteger)time / 60; //分钟
    NSInteger seconds = (NSInteger)time % 60; //秒
    //转换为string
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,seconds];
    
    return string;
}


//图片旋转图片
- (void)startAnimation1111{
    //CALayer动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转的起始值
    animation.fromValue = [NSNumber numberWithFloat:0];
    //旋转的结束值
    animation.toValue = [NSNumber numberWithFloat:M_PI_2];
    //重复次数
    animation.repeatCount = NSIntegerMax;
    //时间
    animation.duration = 5;
    //是否按照结束为止继续旋转
    animation.cumulative = YES;
    [_topImageView.layer addAnimation:animation forKey:@"标记11"];
}

//返回按钮方法
- (void)disMissButtonAction:(UIButton *)button{
    //开辟一个字符串空间
    NSString *isPlay = [NSString string];
    
    if (_isPlay == YES) {
        //返回的时候发送通知 同知小播放界面的状态修改
        [[NSNotificationCenter defaultCenter] postNotificationName:@"isPlay" object:@"isPlay"];
        isPlay = @"NoIsPlay";
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"isPlay" object:@"noIsPlay"];
        isPlay = @"isPlay";
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        //这块的通知必须在页面跳过去后发
        //发通知让图片旋转或者停止旋转
        [[NSNotificationCenter defaultCenter] postNotificationName:@"imageAnimation" object:isPlay];
    }];
    
}


#pragma mark - 控制歌曲播放
- (void)playSongs {
    [HGAVPlayerManager shareHGavPlayerManager].playTimerBlock = ^(CGFloat timer){
        
        //播放时间
        self.initialLabel.text = [self timeToString:timer]; //调用方法，赋值
        //总时间
        self.totalLabel.text = [self timeToString:[HGAVPlayerManager shareHGavPlayerManager].sumTime - timer];
        
              [self playTimer:timer]; //调用方法
        
    };
    
    [HGAVPlayerManager shareHGavPlayerManager].playToEndBlock = ^(){
        NSLog(@"播放完我单例的观察者会观察到 就会调用block 走这个方法, 播放完在这里做你想做的");
        
        //发送下一曲同时
        [[NSNotificationCenter defaultCenter] postNotificationName:@"musicButtonNext" object:nil];
     
        
        // 暂停
        CFTimeInterval stopTime = [self.topImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        // 设置动画速度
        self.topImageView.layer.speed = 0;
        // 保存时间的偏移量
        self.topImageView.layer.timeOffset = stopTime;
      
    };
    
}


- (void)createBackImage{
    
    
    
    self.backImage = [[UIImageView alloc] init];
    _backImage.frame = CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT);
    
   
    [self.view addSubview:_backImage];
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    self.effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
    _effectview.frame = CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT);
    _effectview.alpha = 1;
    
    [_backImage addSubview:_effectview];
    _effectview.userInteractionEnabled = YES;
    
}

        




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
